package com.hk.controller;

import com.hk.entity.Certificates;
import com.hk.entity.Result;
import com.hk.service.CerService;
import com.hk.utils.AliOSSUtils;
import com.hk.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

/**
 * 证书表控制器
 */
@Slf4j
@RestController
@RequestMapping("/Certificates")
public class CerController {
    @Autowired
    private CerService cerService;

    @Autowired
    private AliOSSUtils aliOSSUtils;

    /**
     * 上传证书
     * @param authorization
     * @param title
     * @return
     * @throws Exception
     */
    @PostMapping("/upload")
    private Result uploadCer(@RequestParam("image") MultipartFile image, @RequestHeader("token") String authorization,@RequestParam("title") String title) throws Exception{
        // 从token头中提取JWT令牌
        String token = authorization;
        // 解析JWT令牌并提取学生ID
        Map<String, Object> claims = JwtUtils.parseJWT(token);
        String stuId = (String) claims.get("stuId");
        log.info("文件上传, 文件名: {}", image.getOriginalFilename());
        //调用阿里云OSS工具类进行文件上传
        String url = aliOSSUtils.upload(image);
        cerService.uploadImage(stuId,url,title);
        log.info("文件上传完成,文件访问的url: {}", url);
        return Result.success(url);
    }

    /**
     * 展示该学生的所有证书
     * @param authorization
     * @return
     * @throws Exception
     */
    @GetMapping("/List")
    private Result listCer(@RequestHeader("token") String authorization) throws  Exception{
        // 从token头中提取JWT令牌
        String token = authorization;
        // 解析JWT令牌并提取学生ID
        Map<String, Object> claims = JwtUtils.parseJWT(token);
        String stuId = (String) claims.get("stuId");
        List<Certificates> certificates= cerService.queryAllCer(stuId);
        return Result.success(certificates);
    }
}
